package com.aichess.service.impl;

import com.aichess.service.AIService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Service
public class ChessAIService implements AIService {
    
    @Value("${ai.deepseek.url}")
    private String deepSeekUrl;
    
    @Value("${ai.deepseek.api-key}")
    private String deepSeekApiKey;
    
    @Value("${ai.deepseek.model}")
    private String deepSeekModel;
    
    @Value("${ai.qwen.url}")
    private String qwenUrl;
    
    @Value("${ai.qwen.api-key}")
    private String qwenApiKey;
    
    @Value("${ai.qwen.model}")
    private String qwenModel;
    
    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String getMove(String fen, String player) {
        if ("red".equals(player)) {
            return callDeepSeekAI(fen);
        } else {
            return callQwenAI(fen);
        }
    }

    private String callDeepSeekAI(String fen) {
        try {
            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.set("Authorization", "Bearer " + deepSeekApiKey);
            
            // 构造请求体
            String requestBody = String.format(
                "{\"model\":\"%s\",\"messages\":[{\"role\":\"system\",\"content\":\"你是一个中国象棋大师\"}," +
                "{\"role\":\"user\",\"content\":\"当前棋局状态(FEN格式): %s。请给出下一步的最佳走法，只返回走法格式如'e2e4'，不要返回其他内容。\"}]," +
                "\"stream\":false}",
                deepSeekModel, fen
            );
            
            HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                deepSeekUrl, 
                HttpMethod.POST, 
                request, 
                String.class
            );
            
            // 解析响应
            if (response.getStatusCode() == HttpStatus.OK) {
                // 简化解析 - 实际应用中需要更健壮的JSON解析
                String responseBody = response.getBody();
                if (responseBody != null && responseBody.contains("\"content\":")) {
                    String content = responseBody.split("\"content\":\"")[1].split("\"")[0];
                    // 提取走法部分
                    return content.replaceAll("[^a-h0-9]", "").substring(0, 4);
                }
            }
            return "error";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    private String callQwenAI(String fen) {
        try {
            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.set("Authorization", "Bearer " + qwenApiKey);
            
            // 构造请求体
            String requestBody = String.format(
                "{\"model\":\"%s\",\"input\":{\"messages\":[{\"role\":\"system\",\"content\":\"你是一个中国象棋大师\"}," +
                "{\"role\":\"user\",\"content\":\"当前棋局状态(FEN格式): %s。请给出下一步的最佳走法，只返回走法格式如'e2e4'，不要返回其他内容。\"}]}}",
                qwenModel, fen
            );
            
            HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                qwenUrl, 
                HttpMethod.POST, 
                request, 
                String.class
            );
            
            // 解析响应
            if (response.getStatusCode() == HttpStatus.OK) {
                // 简化解析 - 实际应用中需要更健壮的JSON解析
                String responseBody = response.getBody();
                if (responseBody != null && responseBody.contains("\"output\":")) {
                    String output = responseBody.split("\"output\":")[1].split("\"text\":\"")[1];
                    // 提取走法部分
                    return output.replaceAll("[^a-h0-9]", "").substring(0, 4);
                }
            }
            return "error";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
} 